<script lang="ts" setup>
import moment from 'moment'
import { Cell, CellGroup, Dialog } from 'vant'
import { pickDate } from '~/utils'

defineProps<{
  modelValue: boolean
}>()

const emits = defineEmits([
  'update:dateRange',
  'update:modelValue',
])
const d1 = ref('' as Date | string)
const d2 = ref('' as Date | string)

function chooseDate() {
  const d1ts = (d1.value as Date).valueOf()
  const d2ts = (d2.value as Date).valueOf()
  emits('update:dateRange', d1ts, d2ts)
  close()
}

function close() {
  emits('update:modelValue', false)
}

const valid = computed(() => {
  return d1.value !== '' && d2.value !== ''
})

// const hint = computed(() => {
//   if (!d1.value || !d2.value) {
//     return '请选择日期'
//   }
//   const _t = (ts: number) => moment(ts).format('YYYY-MM-DD')
//   const d1s = _t((d1.value as Date).valueOf())
//   const d2s = _t((d2.value as Date).valueOf())
//   return `从 ${d1s}\n到 ${d2s}`
// })

async function pickStart() {
  const d = d1.value === '' ? (new Date()) : d1.value as Date
  const res = await pickDate(d)
  if (res) {
    d1.value = res
  }
}

async function pickEnd() {
  const d = d2.value === '' ? (new Date()) : d2.value as Date
  const res = await pickDate(d)
  if (res) {
    d2.value = res
  }
}
</script>

<template>
  <div>
    <Dialog
      :show="modelValue"
      title="选择日期"
      :show-confirm-button="valid"
      close-on-click-overlay
      teleport="body"
      :z-index="999"
      @confirm="chooseDate"
      @update:show="$emit('update:modelValue', $event)"
    >
      <CellGroup>
        <Cell
          title="起始时间"
          :value="d1 ? moment(d1).format('YYYY-MM-DD') : '请选择'"
          is-link
          @click="pickStart"
        />
        <Cell
          title="结束时间"
          :value="d2 ? moment(d2).format('YYYY-MM-DD') : '请选择'"
          is-link
          @click="pickEnd"
        />
      </CellGroup>

      <!-- <LxButton title="确认" :disable="!valid" :action="chooseDate" /> -->
    </Dialog>
  </div>
</template>
